import { StoreOptions } from "vuex";
import ACCESS_ENUM from "@/access/accessEnum";
import {UserControllerService} from '../../../generated';
import router from "@/router";
import { Message } from "@arco-design/web-vue";


export default {
  namespaced: true,
  state: () => ({
    curUser: {userRole: ACCESS_ENUM.NOT_LOGIN,}
    // {
    //   userName: '未登录',
    //   userRole: ACCESS_ENUM.NOT_LOGIN,
    //   userAccount: 'admin',
    //   userPassword: 'adminadmin'
    // }
  }),
  actions: {
    loginUser: async ({ commit, state }, user) => {
      const res = await UserControllerService.userLoginUsingPost(user);
      const {code, data} = res;
      console.log('登录 code', res);
      if (code === 0) {
        data.userAccount = user.userAccount;
        data.password = user.password;
        commit('updateUser', data);
        console.log('login27', res);
        sessionStorage.setItem('token', data.token); // 登录成功后保存token
        // 跳转到主页
        router.push({
          path: '/'
        })
      }else {
        commit('updateUser', {...state.curUser, userRole: ACCESS_ENUM.NOT_LOGIN});
      }
    },
    register: async ({ commit, state }, registerParams) => {
      const res = await UserControllerService.userRegisterUsingPost(registerParams);
      const {code, data} = res;
      if (code == 0) {
        // 获取用户信息
        const res =  await UserControllerService.getUserByIdUsingGet(data);
        if (res.code === 0) {
          Message.success('注册成功')
          commit('updateUser', {...res.data, userRole: ACCESS_ENUM.USER});
          // 跳转到登录页面
          router.push({
            path: '/user/login'
          })
        }else {
          Message.error('注册失败')
        }
      }else {
        Message.error('注册失败')
        commit('updateUser', {...state.curUser, userRole: ACCESS_ENUM.NOT_LOGIN});
      }
    },
    setCurUser: ({commit}, user) => {
      commit('updateUser', user);
    }
  },
  mutations: {
    updateUser: (state, user) => {
      state.curUser = user;
      console.log('state,curUser', user);
    }
  }
} as StoreOptions<any>;
